package com.atguigu.gmall.gateway.filter;

import com.atguigu.gmall.common.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2023-06-14 16:09
 */
@Slf4j
@Component
public class AccessFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("被访问了..");
        String token = "";
        //先通过获取到Redis中key过期时间
        Long expire = redisTemplate.getExpire("user:" + token);
        //计算key过期时间 是否小于 规定阈值(少于2小时)
        redisTemplate.expire("user:"+token, 7, TimeUnit.DAYS);


        //获取用户访问IP
        String ipAddress = IpUtil.getGatwayIpAddress(exchange.getRequest());
        //调用百度API获取IP对应行政区域 跟 Redis中存储地址比较

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
